module.exports = function(sequelize, DataTypes) {
  var helper = require('../lib/merge')
  var prototype = require('./mixins/TaskMixin')
  var rating = require('./mixins/RatingMixin')

  var Progress = sequelize.define(
    'Progress',
    helper.mergeWithArray(
      {
        type: {
          type: DataTypes.STRING
        },
        name: {
          type: DataTypes.STRING
        },
        isPublished: {
          type: DataTypes.INTEGER
        },
        finishAt: {
          type: DataTypes.DATE,
          comment: 'Final finish time'
        },
        costSeconds: {
          type: DataTypes.INTEGER,
          comment: 'Total seconds cost in this task'
        },
        correctCount: {
          type: DataTypes.INTEGER,
          comment: 'Total number of correct answers'
        },
        state: {
          type: DataTypes.ENUM('start', 'done', 'check', 'redo'),
          comments: 'State of the task progress'
        },
        unreadCount: {
          type: DataTypes.INTEGER,
          defaultValue: 0,
          comment:
            'Total unread message number on this progress, for teacher > 0, for student < 0'
        }
      },
      prototype(DataTypes).attributes,
      rating(DataTypes).attributes
    ),
    helper.mergeWithArray(
      {
        tableName: 'progresses',
        indexes: [
          {
            name: 'user_id_idx',
            fields: ['userId']
          },
          {
            name: 'group_id_idx',
            fields: ['groupId']
          },
          {
            name: 'task_id_idx',
            fields: ['taskId']
          },
          {
            name: 'document_id_idx',
            fields: ['documentId']
          },
          {
            name: 'version_id_idx',
            fields: ['versionId']
          },
          {
            name: 'state_idx',
            fields: ['state']
          },
          {
            name: 'unread_count_idx',
            fields: ['unreadCount']
          }
        ],
        comments: '用户-任务进度连接表'
      },
      prototype(DataTypes).options,
      rating(DataTypes).options
    )
  )

  Progress.associate = function(models) {
    this.belongsTo(models.Task, {
      as: 'Task',
      foreignKey: 'taskId',
      constraints: false
    })
    this.belongsTo(models.Document, {
      as: 'Prototype',
      foreignKey: 'documentId',
      constraints: false
    })
    this.belongsTo(models.Document, {
      as: 'Version',
      foreignKey: 'versionId',
      constraints: false
    })
    this.belongsTo(models.User, {
      as: 'Owner',
      foreignKey: 'userId',
      constraints: false
    })
    this.belongsTo(models.Group, {
      as: 'Group',
      foreignKey: 'groupId',
      constraints: false
    })
  }

  return Progress
}
